import json
import logging
from django import http
from django.contrib.auth import login, logout
from django.shortcuts import render, redirect
import re
# Create your views here.
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User, Address
from apps.users.utils import generic_verify_url, check_verify_token
from celery_tasks.email.tasks import send_active_email
from utils.response_code import RETCODE


class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')
    def post(self,request):
        data = request.POST
        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        mobile = data.get('mobile')
        sms_code = data.get('sms_code')

        if not all([username,password,password2,mobile]):
            return http.HttpResponseBadRequest('你缺点啥东西~')
        if not re.match(r'[a-zA-Z0-9_-]{5,20}',username):
            return http.HttpResponseBadRequest('大哥,用户名不符合')
        if password != password2:
            return http.HttpResponseBadRequest('密码要一致鸭!')
        if not re.match(r'1[3-9]\d{9}',mobile):
            return http.HttpResponseBadRequest('大哥,手机也要符合规则呀')

        # 数据入库
        # try:
        #     user = User.objects.create_user(username=username,password=password,mobile=mobile)
        # except Exception as e:
        #     logger = logging.getLogger('django')
        #     logger.error(e)
        #
        # login(request, user)
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            logger = logging.getLogger('django')
            logger.error(e)

        # 添加一个方法 来保存登陆的状态
        login(request, user)

        redis_conn = get_redis_connection('code')
        sms_code_redis = redis_conn.get('sms_%s'%mobile)
        if sms_code_redis is None:
            return http.HttpResponseBadRequest('验证码过期了')
        if sms_code != sms_code_redis.decode():
            return http.HttpResponseBadRequest('验证码不正确')


        return redirect(reverse('contents:index'))


class Username(View):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code':0,'errmsg':'ok','count':count})


class mobile(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code':0,'errmsg':'ok','count':count})


class Login(View):
    def get(self,request):
        return render(request,'login.html')
    def post(self,request):

        username = request.POST.get('username')
        password = request.POST.get('pwd')
        next = request.GET.get('next')

        # 接受登陆状态
        remembered = request.POST.get('remembered')

        if not all([username,password]):
            return http.HttpResponseBadRequest('参数不齐')
        if not re.match(r'[a-zA-Z0-9_-]{5,20}', username):
            return http.HttpResponseBadRequest('大哥,用户名不符合')

        # 系统自带的密码验证
        from django.contrib.auth import authenticate
        user = authenticate(username=username,password=password)
        # 正确返回user,错误返回None
        if user is None:
            return http.HttpResponseBadRequest('账号或者密码错误')

        # 保持会话状态
        login(request,user)
        # 判断是否记住登陆
        if remembered == 'on':
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        if next:
            response = redirect(next)
        else:
            response = redirect(reverse("contents:index"))


        response.set_cookie('username',user.username,max_age=3600)

        return response


class LogoutView(View):
    def get(self,request):
        # request.session.flush
        # 吧状态保持的信息删掉
        from django.contrib.auth import logout
        logout(request)
        # 删除cookie中的username信息

        response =redirect(reverse('contents:index'))
        response.delete_cookie('username')
        # 跳转到首页
        return response


from django.contrib.auth.mixins import LoginRequiredMixin

# LoginRequiredMixin可以帮我们做用户登录的验证,如果没有登陆就会跳转到/accounts/login/
# 不想跳到accouts里,要跳到login/里
class CenterView(LoginRequiredMixin,View):
    def get(self,request):
        # 获取登陆用户
        user = request.user
        context = {
            'username' :user.username,
            'mobile':user.mobile,
            'email':user.email,
            'email_active':user.email_active
        }
        return render(request,'user_center_info.html',context=context)

from utils.views import LoginRequiredJSONMixin

# 注册发送邮箱
class EmailView(LoginRequiredJSONMixin,View):
    def put(self,request):
        body = request.body
        body_str = body.decode()
        data =json.loads(body_str)
        email = data.get('email')
        if email is None:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数不全'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数不全'})

        user = request.user
        try:
            user.email = email
            user.save()
        except:
            return http.JsonResponse({'code': RETCODE.DBERR})

        # 使用封装的方法生成激活邮件链接.并对user.id加密
        verify_url=generic_verify_url(user.id)
        # 使用异步执行发送邮件
        send_active_email.delay(email,verify_url)

        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})

# 激活邮箱
class EmailactiveView(View):
    def get(self,request):
        token = request.GET.get('token')
        if token is None:
            return http.HttpResponseBadRequest('获取的token参数错误')
        user_id = check_verify_token(token)
        if user_id is None:
            return http.HttpResponseBadRequest('id参数错误')
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return http.HttpResponseBadRequest('用户不存在')

        user.email_active=True
        user.save()

        return redirect(reverse('users:center'))

# 显示收货地址界面
class AddressView(LoginRequiredMixin,View):
    def get(self,request):
        user = request.user
        addresses=Address.objects.filter(user=user, is_deleted=False)
        addresses_list=[]
        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "province_id": address.province_id,
                "city": address.city.name,
                "city_id": address.city_id,
                "district": address.district.name,
                "district_id": address.district_id,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        context = {
            'addresses':addresses_list,
            'default_address_id':user.default_address
        }
        return render(request,'user_center_site.html',context)


# 新建收货地址
class CreateAddressView(LoginRequiredJSONMixin,View):
    def post(self,request):
        count=Address.objects.filter(user=request.user).count()
        if count > 20:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseBadRequest('参数email有误')

        # 将收集 的数据存入数据库
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

        except Exception:
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'新增地址失败'})



        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 如果没有默认地址,就设置默认地址
        if not request.user.default_address:
            request.user.default_address = address
            request.user.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok','address':address_dict})


class updateAddressView(LoginRequiredJSONMixin,View):
    # 编辑收货地址
    def put(self,request,address_id):
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseBadRequest('参数email有误')

        # 找到编辑的数据,并修改
        Address.objects.filter(id=address_id).update(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )
        # 找到修改后的地址
        address = Address.objects.get(id=address_id)
        address = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'address': address})
    # 删除地址
    def delete(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted=True
            address.save()
        except Exception:
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'删除失败'})
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})


# 设置默认收货地址
class SetDefaultView(LoginRequiredJSONMixin,View):
    def put(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address=address
            request.user.save()
        except Exception:

            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})

# 设置收货地址的标题
class AddressTitleView(LoginRequiredJSONMixin,View):
    def put(self,request,address_id):
        # 接受数据
        json_dict=json.loads(request.body.decode())
        new_title = json_dict.get('title')
        try:
            address = Address.objects.get(id=address_id)
            address.title= new_title
            address.save()
        except Exception:
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'修改标题失败'})
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})

class UserPasswordView(LoginRequiredMixin,View):
    def get(self,request):
        return render(request,'user_center_pass.html')
    def post(self,request):
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        new_password2= request.POST.get('new_password2')

        if not all({old_password,new_password,new_password2}):
            http.HttpResponseBadRequest('参数不齐')
        if new_password != new_password2:
            http.HttpResponseBadRequest('两次密码不一致')

        if not request.user.check_password(old_password):
            return render(request, 'user_center_pass.html', {'origin_password_errmsg': '原始密码错误'})

        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception:
            return render(request, 'user_center_pass.html', {'change_password_errmsg': '修改密码失败'})
        # 5.退出登陆,删除登陆信息
        logout(request)
        # 6.跳转到登陆页面
        response = redirect(reverse('users:login'))

        response.delete_cookie('username')

        return response

